import 'dart:convert';

import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:gw_github_flutter/common/route_name.dart';
import 'package:gw_github_flutter/models/models.dart';
import 'package:lpinyin/lpinyin.dart';

class SliverRouteAZList extends StatefulWidget {
  SliverRouteAZList({Key? key}) : super(key: key);

  @override
  State<SliverRouteAZList> createState() => _SliverRouteAZListState();
}

class _SliverRouteAZListState extends State<SliverRouteAZList> {
  List<CityModel> cityList = [];

  @override
  void initState() {
    super.initState();
    Future.delayed(const Duration(milliseconds: 500), () {
      loadData();
    });
  }

  void loadData() async {
    //加载城市列表
    rootBundle.loadString('assets/data/china.json').then((value) {
      cityList.clear();
      Map countyMap = json.decode(value);
      List list = countyMap['china'];
      for (var v in list) {
        cityList.add(CityModel.fromJson(v));
      }
      _handleList(cityList);
    });
  }

  void _handleList(List<CityModel> list) {
    if (list.isEmpty) return;
    for (int i = 0, length = list.length; i < length; i++) {
      String pinyin = PinyinHelper.getPinyinE(list[i].name);
      String tag = pinyin.substring(0, 1).toUpperCase();
      list[i].namePinyin = pinyin;
      if (RegExp('[A-Z]').hasMatch(tag)) {
        list[i].tagIndex = tag;
      } else {
        list[i].tagIndex = '#';
      }
    }
    // A-Z sort.
    SuspensionUtil.sortListBySuspensionTag(list);

    // show sus tag.
    SuspensionUtil.setShowSuspensionStatus(cityList);

    // add header.
    cityList.insert(
        0,
        CityModel(
            name: 'header', tagIndex: "top")); //index bar support local images.

    setState(() {});
  }

  Widget _buildHeader() {
    List<CityModel> hotCityList = [];
    hotCityList.addAll([
      CityModel(name: "北京市"),
      CityModel(name: "广州市"),
      CityModel(name: "成都市"),
      CityModel(name: "深圳市"),
      CityModel(name: "杭州市"),
      CityModel(name: "武汉市"),
    ]);
    return Padding(
      padding: const EdgeInsets.all(20),
      child: Wrap(
        alignment: WrapAlignment.center,
        runAlignment: WrapAlignment.center,
        spacing: 10.0,
        children: hotCityList.map((e) {
          return OutlinedButton(
            style: ButtonStyle(
              side: MaterialStateProperty.all(
                  const BorderSide(color: Colors.grey, width: .5)),
            ),
            child: Padding(
              padding: EdgeInsets.only(left: 10, right: 10),
              child: Text(e.name),
            ),
            onPressed: () {
              print("OnItemClick: $e");
              Navigator.pop(context, e);
            },
          );
        }).toList(),
      ),
    );
  }

  Widget _body() {
    return Container(
      child: Column(
        children: [
          Expanded(
            child: AzListView(
              data: cityList,
              itemCount: cityList.length,
              itemBuilder: (BuildContext context, int index) {
                if (index == 0) return _buildHeader();
                CityModel model = cityList[index];
                return ListTile(
                  title: Text(model.name),
                  onTap: () {
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text("onTap"),
                        duration: Duration(seconds: 2),
                      ),
                    );
                  },
                );
              },
              susItemHeight: 36,
              susItemBuilder: (BuildContext context, int index) {
                CityModel model = cityList[index];
                String tag = model.getSuspensionTag();
                if ("top" == tag) {
                  return Container();
                }
                return Container(
                  height: 40,
                  width: MediaQuery.of(context).size.width,
                  padding: EdgeInsets.only(left: 16.0),
                  color: Color(0xFFF3F4F5),
                  alignment: Alignment.centerLeft,
                  child: Text(
                    '$tag',
                    softWrap: false,
                    style: const TextStyle(
                      fontSize: 14.0,
                      color: Color(0xFF666666),
                    ),
                  ),
                );
              },
              indexBarData: SuspensionUtil.getTagIndexList(cityList),
              indexBarOptions: const IndexBarOptions(
                needRebuild: true,
                textStyle: TextStyle(
                    fontSize: 10,
                    color: Colors.grey,
                    fontWeight: FontWeight.w500),
                selectTextStyle: TextStyle(
                    fontSize: 12,
                    color: Colors.white,
                    fontWeight: FontWeight.w500),
                selectItemDecoration: BoxDecoration(
                    shape: BoxShape.circle, color: Color(0xFF333333)),
                // color: Colors.transparent,
                // downColor: Color(0xFFEEEEEE),
                indexHintWidth: 96,
                indexHintHeight: 97,
                indexHintDecoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage("imgs/bubble_white.png"),
                    fit: BoxFit.contain,
                  ),
                ),
                indexHintAlignment: Alignment.centerRight,
                indexHintTextStyle:
                    TextStyle(fontSize: 24.0, color: Colors.black87),
                indexHintOffset: Offset(-20, 0),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(RouteName.sliverRoute_AZList),
      ),
      body: _body(),
    );
  }
}
